# -*- coding:utf-8 -*-
import subprocess
from flask import Flask, request
import threading
import git
import StateParam
import catAPI
from urllib import parse

def getprocessnum(pstr=""):
    split = pstr.split(" ")
    # print(split)
    for s in split:
        if (s.isdigit()):
            return s
    return None

def restartmain(robot_wxid, to_wxid):
    print(threading.current_thread().name)
    state, popen = subprocess.getstatusoutput("tasklist |findstr python.exe")
    print(state)
    print("---------------------")
    for prc in popen.split('\n'):
        print(prc)
        processnum = getprocessnum(prc)
        print(processnum)
        state1, popen1 = subprocess.getstatusoutput("wmic process " + processnum)
        print(popen1)
        print("==============="+str(popen1.find("catMain.py")))
        if (popen1.find("catMain.py") != -1):
            call = subprocess.getstatusoutput("taskkill /pid " + processnum + " -f")
            print(call)
            break

    print("启动主任务",robot_wxid, to_wxid)

    msg = catAPI.send_text_msg(robot_wxid, to_wxid, "重启成功！ " )
    state1 = subprocess.call("python "+StateParam.sevicePath+"\catMain.py", shell=True)
    print(state1)


app = Flask(import_name=__name__, static_url_path="/static", static_folder="static")

def test1():
    print(threading.current_thread().name)
    print("okokokok")

@app.route('/restartCat',methods=['GET'])
def restartCat():
    qs = parse.parse_qs(parse.urlparse(request.url).query)
    print(qs)
    t1 = threading.Thread(target=restartmain,args=(qs.get('robot_wxid')[0], qs.get('to_wxid')[0]))
    t1.start()
    return "重启ok"


@app.route('/updateCat',methods=['GET'])
def updateCat():
    g = git.cmd.Git(StateParam.sevicePath)
    return g.pull()

if __name__ == "__main__":
    t1 = threading.Thread(target=restartmain,args=("aa", "bb"))
    t1.start()
    app.run(host="0.0.0.0", port=5001)
